# koroFileHeader at Yungoal acer
# Create: 2022-11-09 16:58:03
# LastEdit: 2022-11-14 17:00:30
"""清空数据重置"""
__author__ = '749B'


if __name__ == '__main__':
    # 导入路径
    from pathlib import Path
    BASE_DIR = Path(__file__).resolve().parent.parent
    import sys
    sys.path.append(BASE_DIR.__str__())
    # Django 初始化
    import django
    from django.conf import settings
    from azure_ea_insights import settings as my_settings
    settings.configure(**{ k: v for k, v in vars(my_settings).items() if k.isupper() })
    django.setup()

from django.contrib.auth import models as auth_models
from django.db.models import Model

from billing import models

def table_clear(model: Model):
    """清空表中的记录并重置自增ID"""
    table_name = model._meta.db_table
    object_name = model._meta.object_name
    model.objects.all().delete()
    from django.db import connection
    with connection.cursor() as cursor:
        engine = cursor.db.settings_dict['ENGINE']
        if engine == 'django.db.backends.sqlite3':
            cursor.execute('UPDATE sqlite_sequence SET seq = 0 WHERE name = %s;', [table_name])
        elif engine == 'django.db.backends.mysql':
            cursor.execute('ALTER TABLE %s AUTO_INCREMENT = 0;', [table_name])
        else:
            print(f'没有该类型数据库重置自增ID的命令: {engine}')
        cursor.fetchone()
    print(f'表中记录已清空: {object_name}')

def main():
    """初始化数据库并重置自增ID
    清空前增加确认
    """
    s = input('确认清空数据库 (Y/N): ')
    if s.upper() != 'Y':
        print('放弃操作，任务终止')
        return

    tables = [
        models.Account, 
        models.Summary, models.Detail, models.PriceSheet, 
        models.Subscriptions, 
        models.CppProduct,
        ]
    for tb in tables:
        table_clear(tb)

    if hasattr(settings, 'AZURE_EA_ACCOUNT'):
        print('发现EA账号信息，直接导入')
        account = models.Account.objects.create(**settings.AZURE_EA_ACCOUNT)
        print(account.name, account.enrollment)

    # 创建超级管理员
    if not auth_models.User.objects.exists():
        username, password = getattr(settings, 'ADMIN_USER_LOGIN', ('admin', 'password'))
        user = auth_models.User.objects.create(username=username, is_staff=True, is_superuser=True)
        user.set_password(password)
        user.save()
        print('createsuperuser:', username)
    else:
        print("未创建用户")


if __name__ == '__main__':
    main()
